package system

import (
	"5title_gin/global"
	"5title_gin/pkg/utils/fileutil"
	"5title_gin/pkg/utils/jwts"
	"5title_gin/pkg/utils/res"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"log"
	"strings"
)

func (api *SystemApi) UploadView(c *gin.Context) {
	zap.S().Info("请求 Content-Type: ", c.Request.Header.Get("Content-Type"))
	file, err := c.FormFile("makefile")
	if file != nil {
		zap.S().Info(file.Filename)
	} else {
		zap.S().Info("文件为空")
		return
	}
	if err != nil {
		res.FailWithError(err, c)
		return
	}
	const (
		KB = 1024
		MB = KB * 1024
	)
	if file.Size > global.Config.Storage.Size*MB {
		res.OkWithMsg("文件大小超出限制", c)
		return
	}
	src, err := file.Open()
	if err != nil {
		res.FailWithError(err, c)
		return
	}
	defer src.Close()
	// 解析 Token 获取 UserID
	tokenString := c.GetHeader("Authorization")
	if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
		res.FailWithMsg("未提供有效的 Token", c)
		return
	}
	tokenString = strings.TrimPrefix(tokenString, "Bearer ")
	claims, err := jwts.CheckToken(tokenString)
	if err != nil {
		res.FailWithMsg("Token 无效或已过期", c)
		return
	}
	userId := claims.Claims.UserID
	ctx := c.Request.Context()
	if global.Storage == nil {
		log.Fatal("Storage 组件未初始化")
	}

	mimeType, err := fileutil.GetMimeType(file.Filename)
	zap.S().Info(mimeType)
	if err != nil {
		res.FailWithError(err, c)
		return
	}
	url, err := global.Storage.UploadFile(ctx, src, file.Filename, mimeType)
	if err != nil {
		res.FailWithError(err, c)
		return
	}
	// 更新数据库中的头像
	result := global.DB.Table("user_models").Where("id = ?", userId).Update("avatar", url)
	if result.Error != nil {
		res.Error("更新用户头像失败", result.Error, c)
		return
	}
	if result.RowsAffected == 0 {
		res.FailWithMsg("用户不存在", c)
		return
	}
	res.OkWithData(url, c)
}
